package com.hitalkie.teacher.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Country;
import com.hitalkie.teacher.model.User;
import com.hitalkie.teacher.util.OkHttpManager;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Date 29/09/2016
 *
 * @author charliema
 */

public class ProfileEditActivity extends BaseActivity {

    private final int REQ_CODE_NAME = 0;
    private final static int REQ_CODE_COUNTRY_HOME = 1;
    private final static int REQ_CODE_COUNTRY_CURRENT = 2;

    private final int REQ_CODE_IMAGE_FROM_GALLERY = 10;
    private final int REQ_CODE_IMAGE_CROP = 12;

    private User mUser = new User();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkSignIn();
        initView();
        getData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQ_CODE_NAME:
                mUser.name = data.getStringExtra(Input1Activity.EXTRA_CONTENT);
                putUser(mUser);
                break;
            case REQ_CODE_COUNTRY_HOME: {
                Country country = (Country) data.getSerializableExtra(CountryListActivity.EXTRA_COUNTRY);
                mUser.home_country = country.name_en;
                putUser(mUser);
                break;
            }
            case REQ_CODE_COUNTRY_CURRENT: {
                Country country = (Country) data.getSerializableExtra(CountryListActivity.EXTRA_COUNTRY);
                mUser.current_country = country.name_en;
                putUser(mUser);
                break;
            }
            case REQ_CODE_IMAGE_FROM_GALLERY: {
                Log.e("MARR", "REQ_CODE_IMAGE_FROM_GALLERY:resultCode:" + resultCode);
                cropImage(data.getData(), 240);
                break;
            }
            case REQ_CODE_IMAGE_CROP: {
                uploadImage(new File(mImagePath + "crop.jpg"));
                break;
            }

        }
    }

    private void checkSignIn() {
        if (!TalkieApplication.isSignIn()) {
            startActivity(new Intent(getActivity(), SignUpActivity.class));
        }
    }

    private void initView() {
        setContentView(R.layout.view_profile_edit);

        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        findViewById(R.id.viewPortrait).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 改头像
                getImageFromGallery();

            }
        });
        findViewById(R.id.viewName).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 改名字
                Intent i = new Intent(getActivity(), Input1Activity.class);
//                i.putExtra(Input1Activity.EXTRA_TITLE, "姓名");
                i.putExtra(Input1Activity.EXTRA_CONTENT, mUser.name);
                startActivityForResult(i, REQ_CODE_NAME);
            }
        });
        findViewById(R.id.viewGender).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 变性
                new AlertDialog.Builder(getActivity())
                        .setTitle("choose gender")
                        .setItems(new String[]{"Male", "Female"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    mUser.gender = 1;
                                } else {
                                    mUser.gender = 2;
                                }
                                putUser(mUser);
                            }
                        })
                        .show();
            }
        });
        findViewById(R.id.viewHomeTown).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 改老家 跳到国家列表页
                startActivityForResult(new Intent().setClass(getActivity(), CountryListActivity.class).putExtra("is_all", true), REQ_CODE_COUNTRY_HOME);
            }
        });
        findViewById(R.id.viewCurrentAt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 现在居住地 跳到国家列表页
                startActivityForResult(new Intent().setClass(getActivity(), CountryListActivity.class).putExtra("is_all", true), REQ_CODE_COUNTRY_CURRENT);
            }
        });
        findViewById(R.id.viewBio).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 修改bio
                final EditText et = new EditText(getActivity());
                et.setText(mUser.detail);
                new AlertDialog.Builder(getActivity())
                        .setTitle("edit the bio")
                        .setView(et)
                        .setPositiveButton("confirm", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                mUser.detail = et.getText().toString();
                                putUser(mUser);
                            }
                        })
                        .show();
            }
        });

    }


    private void getData() {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_ME)
                        //
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();

                        try {
                            final MeResp resp = new Gson().fromJson(jsonStr, MeResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        mUser = resp.user;
                                        updateView();

                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();

                        } finally {
                            // loading dialog
                            loadingDialogFragment.dismiss();
                        }
                    }
                });
    }


    private void putUser(User user) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_ME)
                        //
                        .post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(user)))
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        // loading dialog
                        loadingDialogFragment.dismiss();
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        try {
                            final MeResp resp = new Gson().fromJson(jsonStr, MeResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        Toast.makeText(getActivity(), getText(R.string.update_succeeded), Toast.LENGTH_SHORT).show();
                                        getData();
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            // loading dialog
                            loadingDialogFragment.dismiss();
                        }
                    }
                });
    }


    private static class MeResp extends BaseResponse {
        User user;
    }

    private void updateView() {
        if (!TextUtils.isEmpty(mUser.avatar)) {
            ImageView ivAvatar = (ImageView) findViewById(R.id.ivAvatar);
            Picasso.with(getActivity())
                    .load(mUser.avatar)
                    .placeholder(R.drawable.ic_default_image)
                    .error(R.drawable.ic_default_image)
                    .fit()
                    .into(ivAvatar);
        }

        ((TextView) findViewById(R.id.tvName)).setText(mUser.name);
        ((TextView) findViewById(R.id.tvGender)).setText(mUser.getGender());
        ((TextView) findViewById(R.id.tvLocationCurrent)).setText(mUser.current_country);
        ((TextView) findViewById(R.id.tvLocationHome)).setText(mUser.home_country);

    }


    private void uploadImage(final File file) {
        // 获取七牛地址
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_USER_AVATAR_UPLOAD)
                        //
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        // loading dialog
                        loadingDialogFragment.dismiss();
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "avatar resp:" + jsonStr);

                        try {
                            final UploadResp resp = new Gson().fromJson(jsonStr, UploadResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        // ----------------------七牛上传 ----------------------
                                        //  国内https上传
                                        boolean https = true;
                                        Zone z1 = new AutoZone(null);
//                                        Zone z1 = new AutoZone(null);
                                        Configuration config = new Configuration.Builder().zone(z1).build();

                                        //  海外https上传
//                                        String[] upIps = {"115.231.97.46"};
//                                        ServiceAddress up = new ServiceAddress("https://upload.qbox.me", upIps);
//                                        Zone z0 = new FixedZone(up, null);
//                                        Configuration config = new Configuration.Builder().zone(z0).build();

                                        UploadManager uploadManager = new UploadManager(config);
                                        uploadManager.put(file, resp.key, resp.upload_token,
                                                new UpCompletionHandler() {
                                                    @Override
                                                    public void complete(String key, ResponseInfo info, JSONObject res) {
                                                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                                                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                                                        // TODO 判断是否成功
                                                        mUser.avatar = key;
                                                        putUser(mUser);
                                                    }
                                                }, null);
                                        // ----------------------七牛上传 ----------------------

                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });
                        }
                    }
                });

    }

    private static class UploadResp extends BaseResponse {
        String upload_token;
        String key;
    }


    private String getImagePath() {

        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "ImagePickDir";
        if (!createDir(dirPath)) {
            Toast.makeText(this, "目录已创建", Toast.LENGTH_LONG).show();
        }
        Time time = new Time();
        time.setToNow();
        return dirPath + File.separator + time.format2445() + ".jpg";
    }

    public boolean createDir(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return false;
        }
        File dir = new File(dirPath);
        if (dir.exists() && dir.isDirectory()) {
            return true;
        }
        if (dir.exists() && !dir.isDirectory()) {
            return false;
        }
        if (!dir.exists()) {
            return dir.mkdirs();
        }
        return false;
    }

    private String mImagePath; // the image abs path we output

    private void getImageFromGallery() {

        mImagePath = getImagePath();

        // Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // The system will then launch the best application to select that kind of data for you.

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");

        Uri uri = Uri.fromFile(new File(mImagePath));
        intent.putExtra("return-data", false); // if you want a big image, set return-data false
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // so the uri is "return-data"
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQ_CODE_IMAGE_FROM_GALLERY);
        }

    }

    private void cropImage(Uri uri, int size) {
        Log.e("进入剪裁的uri ：", "" + uri);

        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        // scale h and w
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // output w and h
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);

        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);

        intent.putExtra("noFaceDetection", true);

        intent.putExtra("return-data", false); // if you want a big image, set return-data false
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mImagePath + "crop.jpg"))); // so the uri is "return-data"
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, REQ_CODE_IMAGE_CROP);
    }


}
